package com.example.base.utils

import androidx.lifecycle.MutableLiveData
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import okhttp3.WebSocketListener

object WebSocketClient {

    var webSocket:WebSocket? = null

    val mliveData = MutableLiveData<String>()

    fun start(){
        val request = Request.Builder().url("ws://10.161.9.80:7015/api/websocket/100").build()
        webSocket = OkHttpClient().newWebSocket(request,object:WebSocketListener(){
            override fun onMessage(webSocket: WebSocket, text: String) {
                super.onMessage(webSocket, text)
                mliveData.postValue(text)
            }
        })
    }

    fun sendMessage(msg:String){
        webSocket?.send(msg)
    }

    fun close(){
        webSocket?.close(1000,"关闭")
        webSocket = null
    }
}